<template>
    <view class="page">
        <!-- 顶部大图轮播背景 -->
        <view class="banner-carousel" :style="{ position: 'fixed', zIndex: 1, opacity: bannerOpacity }">
            <swiper class="banner-swiper" circular autoplay interval="4000" indicator-dots
                indicator-active-color="#fff">
                <swiper-item v-for="(banner, index) in bannerImages" :key="index">
                    <image class="banner-image" :src="banner" mode="aspectFill"></image>
                </swiper-item>
            </swiper>
            <!-- 顶部导航栏 - 叠加在轮播图上 -->
            <view class="navbar-overlay">
                <view class="navbar-title">民宿预订</view>
                <view class="navbar-actions">
                    <uni-icon class="navbar-icon" type="search" size="24" color="#fff"></uni-icon>
                    <uni-icon class="navbar-icon" type="heart" size="24" color="#fff"></uni-icon>
                </view>
            </view>
        </view>

        <!-- 滚动视图区域 -->
        <scroll-view scroll-y="true" style="height: 100vh;position: fixed;z-index: 99;" enable-back-to-top="true"
            class="content-scroll" @scroll="onScrollViewScroll" @scrolltolower="loadMoreData" lower-threshold="100">

            <!-- 搜索区域 -->
            <view class="search-section">
                <view class="search-bar">
                    <uni-icon class="search-icon" type="search" size="20" color="#999"></uni-icon>
                    <input class="search-input" type="text" placeholder="搜索目的地、民宿名称" v-model="searchKeyword" />
                </view>

                <!-- 日期选择区域 -->
                <view class="date-selector">
                    <view class="date-item" @click="showCheckInDatePicker = true">
                        <text class="date-label">入住</text>
                        <text class="date-value">{{ checkInDate || '请选择' }}</text>
                    </view>
                    <uni-icon class="date-separator" type="arrowright" size="20" color="#ddd"></uni-icon>
                    <view class="date-item" @click="showCheckOutDatePicker = true">
                        <text class="date-label">离店</text>
                        <text class="date-value">{{ checkOutDate || '请选择' }}</text>
                    </view>
                </view>

                <!-- 位置选择区域 -->
                <view class="location-selector" @click="showLocationPicker = true">
                    <uni-icon class="location-icon" type="map" size="20" color="#999"></uni-icon>
                    <text class="location-text">{{ selectedLocation || '当前位置' }}</text>
                    <uni-icon class="location-arrow" type="arrowright" size="18" color="#999"></uni-icon>
                </view>

                <view class="filter-tags">
                    <view v-for="tag in filterTags" :key="tag.id" class="filter-tag"
                        :class="{ active: selectedTag === tag.id }" @click="selectedTag = tag.id">
                        {{ tag.name }}
                    </view>
                </view>
            </view>

            <!-- 推荐活动 -->
            <view class="activity-section">
                <view class="section-header">
                    <text class="section-title">限时特惠</text>
                    <text class="section-more">更多 ></text>
                </view>
                <swiper class="activity-swiper" circular autoplay interval="3000">
                    <swiper-item v-for="(activity, index) in activities" :key="index">
                        <view class="activity-card">
                            <image class="activity-image" :src="activity.image" mode="aspectFill"></image>
                            <view class="activity-info">
                                <text class="activity-title">{{ activity.title }}</text>
                                <text class="activity-desc">{{ activity.description }}</text>
                                <view class="activity-price">
                                    <text class="price-symbol">¥</text>
                                    <text class="price-value">{{ activity.price }}</text>
                                    <text class="price-unit">起/晚</text>
                                </view>
                            </view>
                        </view>
                    </swiper-item>
                </swiper>
            </view>

            <!-- 民宿列表 -->
            <view class="hotel-section">
                <view class="section-header">
                    <text class="section-title">热门民宿</text>
                    <view class="sort-options">
                        <text v-for="sort in sortOptions" :key="sort.id" class="sort-option"
                            :class="{ active: selectedSort === sort.id }" @click="selectedSort = sort.id">
                            {{ sort.name }}
                        </text>
                    </view>
                </view>
                <!-- 双列瀑布流布局 -->
                <view class="waterfall-container">
                    <up-waterfall v-model="flowList" columns="2">
                        <template v-slot:column="{ leftColumnHotels, colIndex }">
                            <view v-for="(item, index) in leftColumnHotels" :key="index">
                                <!-- 这里编写您的内容，item为您传递给v-model的数组元素 -->
                            </view>
                        </template>
                    </up-waterfall>

                    <!-- 左列 -->
                    <view class="waterfall-column">
                        <view v-for="(hotel, index) in leftColumnHotels" :key="hotel.id" class="hotel-card"
                            @click="viewHotelDetail(hotel.id)">
                            <view class="hotel-image-container">
                                <image class="hotel-image" :src="hotel.image" mode="aspectFill"></image>
                                <view class="hotel-badge" v-if="hotel.badge">{{ hotel.badge }}</view>
                                <uni-icon class="hotel-favorite" :type="hotel.isFavorite ? 'heart-filled' : 'heart'"
                                    size="20" color="#fff" @click.stop="toggleFavorite(hotel.id)"></uni-icon>
                            </view>
                            <view class="hotel-info">
                                <view class="hotel-name">{{ hotel.name }}</view>
                                <view class="hotel-tags">
                                    <text v-for="(tag, tagIndex) in hotel.tags.slice(0, 3)" :key="tagIndex"
                                        class="hotel-tag">
                                        {{ tag }}
                                    </text>
                                </view>
                                <view class="hotel-rating">
                                    <uni-rate :value="hotel.rating" disabled size="14" activeColor="#FFB800"></uni-rate>
                                    <text class="rating-text">{{ hotel.rating }} ({{ hotel.reviewCount }}条评价)</text>
                                </view>
                                <view class="hotel-price-row">
                                    <view class="hotel-price">
                                        <text class="price-symbol">¥</text>
                                        <text class="price-value">{{ hotel.price }}</text>
                                        <text class="price-unit">/晚</text>
                                    </view>
                                    <view class="hotel-location">
                                        <uni-icon type="map" size="14" color="#666"></uni-icon>
                                        <text class="location-text">{{ hotel.distance }}km</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <!-- 右列 -->
                    <view class="waterfall-column">
                        <view v-for="(hotel, index) in rightColumnHotels" :key="hotel.id" class="hotel-card"
                            @click="viewHotelDetail(hotel.id)">
                            <view class="hotel-image-container">
                                <image class="hotel-image" :src="hotel.image" mode="aspectFill"></image>
                                <view class="hotel-badge" v-if="hotel.badge">{{ hotel.badge }}</view>
                                <uni-icon class="hotel-favorite" :type="hotel.isFavorite ? 'heart-filled' : 'heart'"
                                    size="20" color="#fff" @click.stop="toggleFavorite(hotel.id)"></uni-icon>
                            </view>
                            <view class="hotel-info">
                                <view class="hotel-name">{{ hotel.name }}</view>
                                <view class="hotel-tags">
                                    <text v-for="(tag, tagIndex) in hotel.tags.slice(0, 3)" :key="tagIndex"
                                        class="hotel-tag">
                                        {{ tag }}
                                    </text>
                                </view>
                                <view class="hotel-rating">
                                    <uni-rate :value="hotel.rating" disabled size="14" activeColor="#FFB800"></uni-rate>
                                    <text class="rating-text">{{ hotel.rating }} ({{ hotel.reviewCount }}条评价)</text>
                                </view>
                                <view class="hotel-price-row">
                                    <view class="hotel-price">
                                        <text class="price-symbol">¥</text>
                                        <text class="price-value">{{ hotel.price }}</text>
                                        <text class="price-unit">/晚</text>
                                    </view>
                                    <view class="hotel-location">
                                        <uni-icon type="map" size="14" color="#666"></uni-icon>
                                        <text class="location-text">{{ hotel.distance }}km</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 加载更多提示 -->
                <view class="load-more-container" v-if="hotels.length > 0">
                    <view v-if="isLoading" class="loading-indicator">
                        <uni-icon type="spinner" size="24" color="#999" animation="spin"></uni-icon>
                        <text class="loading-text">加载中...</text>
                    </view>
                    <view v-else-if="!hasMore" class="no-more">
                        <text>没有更多数据了</text>
                    </view>
                </view>

            </view>
        </scroll-view>

        <!-- 日期选择器组件 -->
        <uni-date-picker v-model="checkInDate" type="date" :show="showCheckInDatePicker"
            :start-date="new Date().toISOString().split('T')[0]" @confirm="handleCheckInDateChange"
            @cancel="showCheckInDatePicker = false"></uni-date-picker>

        <uni-date-picker v-model="checkOutDate" type="date" :show="showCheckOutDatePicker"
            :start-date="checkInDate || new Date().toISOString().split('T')[0]" @confirm="handleCheckOutDateChange"
            @cancel="showCheckOutDatePicker = false"></uni-date-picker>

        <!-- 位置选择器弹窗（简化版） -->
        <view v-if="showLocationPicker" class="location-picker-overlay" @click="showLocationPicker = false">
            <view class="location-picker-content" @click.stop>
                <view class="location-picker-header">
                    <text class="location-picker-title">选择位置</text>
                    <uni-icon class="location-picker-close" type="close" size="24" color="#999"
                        @click="showLocationPicker = false"></uni-icon>
                </view>
                <view class="location-picker-body">
                    <view class="location-item" @click="selectedLocation = '北京市'; showLocationPicker = false">北京市</view>
                    <view class="location-item" @click="selectedLocation = '上海市'; showLocationPicker = false">上海市</view>
                    <view class="location-item" @click="selectedLocation = '广州市'; showLocationPicker = false">广州市</view>
                    <view class="location-item" @click="selectedLocation = '深圳市'; showLocationPicker = false">深圳市</view>
                    <view class="location-item" @click="selectedLocation = '成都市'; showLocationPicker = false">成都市</view>
                    <view class="location-item" @click="selectedLocation = '杭州市'; showLocationPicker = false">杭州市</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue';

export default {
    name: 'ticket',
    setup() {
        // 轮播图透明度
        const bannerOpacity = ref(1);
        // 最大滚动距离（超过这个距离后完全隐藏）
        const maxScrollDistance = 300; // 可以根据需要调整

        // 加载更多相关状态
        const isLoading = ref(false);
        const hasMore = ref(true);
        const currentPage = ref(1);
        const pageSize = ref(6);

        // 处理滚动视图的滚动事件
        const onScrollViewScroll = (e) => {
            // 从事件对象中获取滚动距离
            const scrollTop = e.detail.scrollTop;

            // 计算透明度（随着滚动距离增加而减小）
            if (scrollTop <= maxScrollDistance) {
                bannerOpacity.value = 1 - scrollTop / maxScrollDistance;
            } else {
                bannerOpacity.value = 0;
            }
        };

        // 搜索相关数据
        const searchKeyword = ref('');
        const selectedTag = ref('all');
        const selectedSort = ref('recommend');

        // 日期选择相关数据
        const checkInDate = ref('');
        const checkOutDate = ref('');
        const showCheckInDatePicker = ref(false);
        const showCheckOutDatePicker = ref(false);

        // 位置选择相关数据
        const selectedLocation = ref('');
        const showLocationPicker = ref(false);

        // 处理日期选择
        const handleCheckInDateChange = (e) => {
            checkInDate.value = formatDate(e.detail.value);
            showCheckInDatePicker.value = false;
        };

        const handleCheckOutDateChange = (e) => {
            checkOutDate.value = formatDate(e.detail.value);
            showCheckOutDatePicker.value = false;
        };

        // 处理位置选择
        const handleLocationSelect = () => {
            // 这里可以根据实际情况实现位置选择逻辑
            // 例如打开地图选择器或城市列表
            selectedLocation.value = '上海市';
            showLocationPicker.value = false;
        };

        // 格式化日期函数
        const formatDate = (date) => {
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        };

        // 筛选标签
        const filterTags = ref([
            { id: 'all', name: '全部' },
            { id: 'popular', name: '热门' },
            { id: 'nearby', name: '附近' },
            { id: 'new', name: '新上线' },
            { id: 'discount', name: '特惠' }
        ]);

        // 排序选项
        const sortOptions = ref([
            { id: 'recommend', name: '推荐' },
            { id: 'price-asc', name: '价格↑' },
            { id: 'price-desc', name: '价格↓' },
            { id: 'rating', name: '评分' }
        ]);

        // 轮播图数据
        const bannerImages = ref([
            'https://img95.699pic.com/xsj/2o/vc/hx.jpg!/fh/600',
            'https://img95.699pic.com/xsj/l3/dl/om.jpg!/fh/600',
            'https://img95.699pic.com/xsj/0n/2r/5b.jpg!/fh/600'
        ]);

        // 活动数据
        const activities = ref([
            {
                id: 1,
                title: '夏日海岛特惠',
                description: '精选海岛民宿，立减200元',
                price: 399,
                image: 'https://img95.699pic.com/xsj/2o/vc/hx.jpg!/fh/300'
            },
            {
                id: 2,
                title: '周末微度假',
                description: '城市周边民宿，享8折优惠',
                price: 299,
                image: 'https://img95.699pic.com/xsj/l3/dl/om.jpg!/fh/300'
            },
            {
                id: 3,
                title: '毕业旅行季',
                description: '学生专享，青春不散场',
                price: 499,
                image: 'https://img95.699pic.com/xsj/0n/2r/5b.jpg!/fh/300'
            }
        ]);

        // 模拟的民宿数据生成函数
        const generateMockHotels = (page, size) => {
            const mockHotels = [];
            const startId = (page - 1) * size + 1;

            for (let i = 0; i < size; i++) {
                const id = startId + i;
                mockHotels.push({
                    id: id,
                    name: `民宿 ${id}`,
                    image: `https://img95.699pic.com/xsj/${['1r/c6/3v', '2o/vc/hx', 'l3/dl/om', '0n/2r/5b'][id % 4]}.jpg!/fh/300`,
                    tags: [
                        ['精品民宿', '经济实惠', '豪华套房'][id % 3],
                        ['山景房', '海景房', '湖景房'][id % 3],
                        ['免费停车', '24小时前台', '早餐包含'][id % 3],
                        ['可携带宠物', '亲子活动', '健身设施'][id % 3]
                    ],
                    rating: (4.5 + (id % 10) * 0.1).toFixed(1),
                    reviewCount: 100 + (id % 500),
                    price: 399 + (id % 10) * 100,
                    distance: (1 + id % 20).toFixed(1),
                    badge: id % 5 === 0 ? ['首单立减', '周末特惠', '长住优惠'][id % 3] : null,
                    isFavorite: id % 7 === 0
                });
            }

            return mockHotels;
        };

        // 民宿数据
        const hotels = ref(generateMockHotels(1, pageSize.value));

        // 加载更多数据的函数
        const loadMoreData = () => {
            // 防止重复加载和没有更多数据时继续加载
            if (isLoading.value || !hasMore.value) {
                return;
            }

            isLoading.value = true;

            // 模拟网络请求延迟
            setTimeout(() => {
                currentPage.value++;
                const newHotels = generateMockHotels(currentPage.value, pageSize.value);

                // 将新数据添加到现有数据中
                hotels.value.push(...newHotels);

                // 模拟数据加载完毕（假设只有5页数据）
                if (currentPage.value >= 5) {
                    hasMore.value = false;
                }

                isLoading.value = false;
            }, 1000);
        };

        // 查看民宿详情
        const viewHotelDetail = (hotelId) => {
            console.log('查看民宿详情:', hotelId);
        };

        // 切换收藏状态
        const toggleFavorite = (hotelId) => {
            const hotel = hotels.value.find(h => h.id === hotelId);
            if (hotel) {
                hotel.isFavorite = !hotel.isFavorite;
            }
        };

        // 瀑布流计算属性 - 将数据分为两列
        const leftColumnHotels = computed(() => {
            return hotels.value.filter((_, index) => index % 2 === 0);
        });

        const rightColumnHotels = computed(() => {
            return hotels.value.filter((_, index) => index % 2 === 1);
        });

        // 移除页面滚动事件监听，因为我们使用的是scroll-view组件

        return {
            searchKeyword,
            selectedTag,
            selectedSort,
            filterTags,
            sortOptions,
            activities,
            hotels,
            leftColumnHotels,
            rightColumnHotels,
            viewHotelDetail,
            toggleFavorite,
            bannerImages,
            bannerOpacity,
            onScrollViewScroll,
            isLoading,
            hasMore,
            loadMoreData,
            // 日期选择相关
            checkInDate,
            checkOutDate,
            showCheckInDatePicker,
            showCheckOutDatePicker,
            handleCheckInDateChange,
            handleCheckOutDateChange,
            // 位置选择相关
            selectedLocation,
            showLocationPicker,
            handleLocationSelect
        };
    }
};
</script>

<style scoped lang="less">
@import './ticket.less';
</style>